package com.example.teacher.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.teacher.entity.EduCourse;
import com.example.teacher.entity.History;
import com.example.teacher.entity.course.HistoryCourse;
import com.example.teacher.mapper.HistoryMapper;
import com.example.teacher.service.EduCourseService;
import com.example.teacher.service.HistoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 江晨晖
 * @since 2022-07-07
 */
@Service
public class HistoryServiceImpl extends ServiceImpl<HistoryMapper, History> implements HistoryService {

    @Autowired
    private EduCourseService courseService;

    @Override
    public Map<String, Object> getFrontHistory(Page<History> pageCourse,String title) {
        //根据更新时间降序排序
        QueryWrapper<History> wrapper =new QueryWrapper<>();
        if (!StringUtil.isNullOrEmpty(title)){
            wrapper.like("title",title);
        }
        wrapper.orderByDesc("gmt_modified");
        Page<History> historyPage = baseMapper.selectPage(pageCourse, wrapper);
        List<History> records = historyPage.getRecords();
        long current = historyPage.getCurrent();
        long pages = historyPage.getPages();
        if (pages==0){
            pages=pages+1;
        }
        long size = historyPage.getSize();
        long total = historyPage.getTotal();
        boolean hasNext = historyPage.hasNext();
        boolean hasPrevious = historyPage.hasPrevious();
        //封装数据
        List<HistoryCourse> list =new ArrayList<>();
        for (History history : records) {
            String courseId = history.getCourseId();
            EduCourse eduCourse = courseService.getById(courseId);
            HistoryCourse historyCourse =new HistoryCourse();
            BeanUtils.copyProperties(eduCourse,historyCourse);
            historyCourse.setVideoId(history.getVideoId());
            list.add(historyCourse);
        }
        //封装成前端要的数据
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("items", list);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);
        return map;
    }
}
